import os
from typing import Dict, List, Optional
from pydantic import BaseSettings


class SpeechConfig(BaseSettings):
    """语音识别配置"""
    
    # FunASR相关配置
    FUNASR_MODEL_DIR: str = "./models/funasr"  # 模型存储目录
    FUNASR_CACHE_DIR: str = "./cache/funasr"   # 缓存目录
    
    # 支持的模型列表
    SUPPORTED_MODELS: List[str] = [
        "sensevoice-small",
        "paraformer-zh", 
        "paraformer-zh-streaming"
    ]
    
    # 默认模型配置
    DEFAULT_MODEL: str = "sensevoice-small"
    DEFAULT_LANGUAGE: str = "zh"
    
    # 文件上传配置
    UPLOAD_DIR: str = "./uploads/speech"       # 上传文件存储目录
    MAX_FILE_SIZE: int = 100 * 1024 * 1024    # 最大文件大小：100MB
    ALLOWED_EXTENSIONS: List[str] = [".wav", ".mp3", ".flac", ".m4a", ".aac"]
    
    # 音频处理配置
    MAX_AUDIO_DURATION: int = 600              # 最大音频时长：10分钟
    SAMPLE_RATE: int = 16000                   # 采样率
    CHUNK_SIZE: int = 960                      # 流式识别块大小
    
    # 识别参数配置
    DEFAULT_USE_VAD: bool = True               # 是否使用语音活动检测
    DEFAULT_USE_PUNC: bool = True              # 是否添加标点符号
    DEFAULT_USE_ITN: bool = True               # 是否使用逆文本归一化
    
    # 缓存配置
    REDIS_EXPIRE_TIME: int = 3600              # Redis缓存过期时间：1小时
    SESSION_TIMEOUT: int = 300                 # 会话超时时间：5分钟
    
    # 性能配置
    MAX_CONCURRENT_REQUESTS: int = 10          # 最大并发请求数
    RECOGNITION_TIMEOUT: int = 60              # 识别超时时间：60秒
    
    # WebSocket配置
    WS_HEARTBEAT_INTERVAL: int = 30            # WebSocket心跳间隔：30秒
    WS_MAX_MESSAGE_SIZE: int = 1024 * 1024     # WebSocket最大消息大小：1MB
    
    # ==================== 新增：API密钥相关配置 ====================
    # API密钥配置
    API_KEY_LENGTH: int = 32                   # API密钥长度
    API_SECRET_LENGTH: int = 64                # API密钥密码长度
    API_KEY_PREFIX: str = "ak_"                # API密钥前缀
    API_SECRET_PREFIX: str = "sk_"             # API密钥密码前缀
    
    # ==================== 新增：配额相关配置 ====================
    # 配额管理配置
    DEFAULT_MONTHLY_QUOTA: int = 1000          # 默认月度配额（单位：分钟）
    QUOTA_CHECK_INTERVAL: int = 60             # 配额检查间隔（秒）
    QUOTA_WARNING_THRESHOLD: float = 0.8       # 配额警告阈值（80%）
    QUOTA_ALERT_THRESHOLD: float = 0.95        # 配额告警阈值（95%）
    
    # 不同客户端类型的默认配额
    DEFAULT_QUOTAS_BY_TYPE: Dict[str, int] = {
        "personal": 100,        # 个人用户：100分钟/月
        "enterprise": 5000,     # 企业用户：5000分钟/月
        "developer": 500        # 开发者用户：500分钟/月
    }
    
    # ==================== 新增：回调相关配置 ====================
    # 回调配置
    CALLBACK_TIMEOUT: int = 30                 # 回调超时时间（秒）
    CALLBACK_RETRY_TIMES: int = 3              # 回调重试次数
    CALLBACK_RETRY_DELAY: int = 5              # 回调重试延迟（秒）
    CALLBACK_MAX_CONCURRENT: int = 10          # 最大并发回调数
    
    # 支持的回调事件类型
    CALLBACK_EVENTS: List[str] = [
        "started",              # 识别开始
        "processing",           # 识别处理中
        "completed",            # 识别完成
        "failed"                # 识别失败
    ]
    
    # ==================== 新增：安全相关配置 ====================
    # 安全配置
    MAX_API_REQUESTS_PER_MINUTE: int = 60      # 每分钟最大API请求数
    MAX_API_REQUESTS_PER_HOUR: int = 1000      # 每小时最大API请求数
    IP_WHITELIST_ENABLED: bool = True          # 是否启用IP白名单
    SIGNATURE_REQUIRED: bool = True            # 是否要求签名验证
    
    # JWT令牌配置（用于临时访问令牌）
    API_TOKEN_EXPIRE_MINUTES: int = 60         # API临时令牌过期时间（分钟）
    API_TOKEN_SECRET_KEY: str = "speech_api_secret_key_2024"  # 令牌签名密钥
    
    # ==================== 新增：客户端用户配置 ====================
    # 客户端用户配置
    CLIENT_USER_NAME_MAX_LENGTH: int = 100     # 用户名最大长度
    CLIENT_USER_EMAIL_MAX_LENGTH: int = 255    # 邮箱最大长度
    CLIENT_USER_COMPANY_MAX_LENGTH: int = 200  # 公司名最大长度
    
    # 支持的客户端类型
    CLIENT_TYPES: List[str] = ["personal", "enterprise", "developer"]
    
    # 支持的客户端状态
    CLIENT_STATUS: List[str] = ["active", "suspended", "inactive"]
    
    # ==================== 新增：使用统计配置 ====================
    # 使用统计配置
    USAGE_STATS_RETENTION_DAYS: int = 365     # 使用统计保留天数
    USAGE_BATCH_SIZE: int = 1000               # 批量处理使用统计的大小
    USAGE_REPORT_TIMEZONE: str = "Asia/Shanghai"  # 报告时区
    
    # 计费相关配置
    BILLING_UNIT: str = "minute"               # 计费单位（分钟）
    BILLING_PRECISION: int = 2                 # 计费精度（小数点后位数）
    
    # 模型路径映射
    MODEL_PATHS: Dict[str, str] = {
        "sensevoice-small": "iic/SenseVoiceSmall",
        "paraformer-zh": "damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
        "paraformer-zh-streaming": "damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online"
    }
    
    # 模型配置参数
    MODEL_CONFIGS: Dict[str, Dict] = {
        "sensevoice-small": {
            "use_vad": True,
            "use_punc": True,
            "use_itn": True,
            "batch_size": 1,
            "device": "cpu"  # 或 "cuda" if GPU available
        },
        "paraformer-zh": {
            "use_vad": True,
            "use_punc": True,
            "use_itn": True,
            "batch_size": 1,
            "device": "cpu"
        },
        "paraformer-zh-streaming": {
            "use_vad": True,
            "use_punc": True,
            "use_itn": True,
            "chunk_size": 960,
            "device": "cpu"
        }
    }
    
    # 语言配置
    LANGUAGE_CONFIGS: Dict[str, Dict] = {
        "zh": {"name": "中文", "code": "zh-cn"},
        "en": {"name": "英文", "code": "en-us"},
        "yue": {"name": "粤语", "code": "zh-yue"},
        "ja": {"name": "日语", "code": "ja-jp"},
        "ko": {"name": "韩语", "code": "ko-kr"},
        "auto": {"name": "自动检测", "code": "auto"}
    }
    
    class Config:
        env_prefix = "SPEECH_"
        case_sensitive = True


# 创建配置实例
speech_config = SpeechConfig()


def get_speech_config() -> SpeechConfig:
    """获取语音识别配置"""
    return speech_config


def validate_model_name(model_name: str) -> bool:
    """验证模型名称是否支持"""
    return model_name in speech_config.SUPPORTED_MODELS


def validate_language(language: str) -> bool:
    """验证语言代码是否支持"""
    return language in speech_config.LANGUAGE_CONFIGS


def validate_file_extension(filename: str) -> bool:
    """验证文件扩展名是否支持"""
    _, ext = os.path.splitext(filename.lower())
    return ext in speech_config.ALLOWED_EXTENSIONS


def get_model_config(model_name: str) -> Optional[Dict]:
    """获取指定模型的配置"""
    return speech_config.MODEL_CONFIGS.get(model_name)


def get_model_path(model_name: str) -> Optional[str]:
    """获取指定模型的路径"""
    return speech_config.MODEL_PATHS.get(model_name)


# ==================== 新增：配额和客户端相关函数 ====================
def get_default_quota_by_type(client_type: str) -> int:
    """根据客户端类型获取默认配额"""
    return speech_config.DEFAULT_QUOTAS_BY_TYPE.get(client_type, speech_config.DEFAULT_MONTHLY_QUOTA)


def validate_client_type(client_type: str) -> bool:
    """验证客户端类型是否支持"""
    return client_type in speech_config.CLIENT_TYPES


def validate_client_status(status: str) -> bool:
    """验证客户端状态是否有效"""
    return status in speech_config.CLIENT_STATUS


def validate_callback_event(event: str) -> bool:
    """验证回调事件类型是否支持"""
    return event in speech_config.CALLBACK_EVENTS


def ensure_directories():
    """确保必要的目录存在"""
    directories = [
        speech_config.FUNASR_MODEL_DIR,
        speech_config.FUNASR_CACHE_DIR,
        speech_config.UPLOAD_DIR
    ]
    
    for directory in directories:
        os.makedirs(directory, exist_ok=True)


# 初始化时创建必要目录
ensure_directories() 